import paramiko
import time

from django.core.paginator import Paginator
from django.db.models import Q
from django.shortcuts import render, redirect, HttpResponse

from .models import Vm, Vm_hm
from .models import machine, Users, conf, Command, Menu, Users_role, Role, Role_menu, Users_group, Users_group_hm, \
    Users_group_relevance, Host_Machine, Pipelinetemplates


# def auth(func):
#     def inner(reqeust):
#         v = reqeust.COOKIES.get('asd')
#         user = reqeust.GET.get('user')
#         user_obj = Users.objects.get(username=user)
#         b = int(int(time.time()) / 86400) * 1024 * int(user_obj.id)
#         if not v:
#             return redirect('/login/')
#         if b != int(v):
#             return redirect('/login/')
#         return func(reqeust, b)
#     return inner


def login(request):
    error_msg = ''
    close = request.GET.get('close')
    if close:
        cookrole = ''
        cookuser = ''
        res = redirect('/login/')
        res.set_cookie('asd', cookuser)
        res.set_cookie('qwe', cookrole)
        return res

    if request.method == 'POST':
        names = request.POST.get('name')  # 获取登陆用户
        pwd = request.POST.get('pwd')  # 获取填写的密码
        ret = Users.objects.filter(name=names, pwd=pwd)
        if ret:
            user_obj = Users.objects.get(name=names)
            user_role_obj = Users_role.objects.get(userid=user_obj.id)
            role_obj = Role.objects.get(id=user_role_obj.roleid)
            cookuser = int(int(time.time())/86400) * 1024 * int(user_obj.id)
            cookrole = 333 * int(int(time.time()) / 86400) * int(role_obj.jurisdiction)
            user = user_obj.name
            res = redirect('/systemctl/product?list=1&user=' + user)
            res.set_cookie('asd', cookuser)
            res.set_cookie('qwe', cookrole)
            return res
            # 验证成功跳转
        else:
            error_msg = '账户或密码错误'

    return render(request, 'login.html', {'error_msg': error_msg})


def auth(func):
    def inner(reqeust):
        v = reqeust.COOKIES.get('asd')
        user = reqeust.GET.get('user')
        user_obj = Users.objects.get(name=user)
        b = int(int(time.time()) / 86400) * 1024 * int(user_obj.id)
        if not v:
            return redirect('/login/')
        if b != int(v):
            return redirect('/login/')
        cookies = int(reqeust.COOKIES.get('qwe'))
        jurisdic = int(cookies / 333 / int(int(time.time()) / 86400))
        if not cookies:
            return redirect('/login/')

        role_obj = Role.objects.get(jurisdiction=jurisdic)
        if not role_obj:
            return redirect('/login/')
        return func(reqeust)
    return inner

#菜单权限
def menu(reqeust):
    cookies = int(reqeust.COOKIES.get('qwe'))
    jurisdic = int(cookies / 333 / int(int(time.time()) / 86400))
    if not cookies:
        return redirect('/login/')

    role_obj = Role.objects.get(jurisdiction=jurisdic)
    if not role_obj:
        return redirect('/login/')
    # 权限菜单
    menu_obj = Role_menu.objects.filter(roleid=role_obj.id)
    menu = Menu.objects.none()
    for menulist in menu_obj:
        menuname = Menu.objects.filter(id=menulist.menuid)
        menu = menu | menuname
    return menu

#产品线权限
def host_machine_ret(reqeust):
    user = reqeust.GET.get('user')
    user_obj = Users.objects.get(name=user)
    usersgroup = Users_group_relevance.objects.filter(usersid=user_obj.id)

    product = Users_group_hm.objects.none()
    for group in usersgroup:
        productname = Users_group_hm.objects.filter(groupid=group.groupid)
        product = product | productname

    ret = Host_Machine.objects.none()
    for productids in product:
        retid = Host_Machine.objects.filter(id=productids.hmid)
        ret = ret | retid
    productret = ret.distinct()  # 去重
    return productret.order_by('name')


#git仓库权限
def vm(request):
    host_machine_rets = host_machine_ret(request)
    retvms = Vm.objects.none()
    hmidvm = Vm_hm.objects.none()
    for hm in host_machine_rets:
        hmid = Vm_hm.objects.filter(hmid=hm.id)
        hmidvm = hmidvm | hmid

    for vmall in hmidvm:
        vms = Vm.objects.filter(id=vmall.vmid)
        retvms = retvms | vms
    return retvms.order_by('name')


@auth
def product(request):
    list = request.GET.get('list')
    user = request.GET.get('user')
    menus = menu(request)
    error_msg = ''
    productrets = host_machine_ret(request)

    page = Paginator(productrets, 10)
    page_id = request.GET.get('page_id')
    if page_id == None:
        page_id = 1
    stus = page.page(int(page_id))
    return render(request, 'product.html',{'ret': stus, 'error_msg': error_msg, 'pageid': int(page_id),'page': page, 'menu': menus, 'list': int(list), 'user': user})




@auth
def back(request):
    list = request.GET.get('list')
    user = request.GET.get('user')
    menus = menu(request)
    error_msg = ''
    names = request.GET.get('name')

    if names == None or 0 == len(names):
        ret = machine.objects.all().order_by("-create_date")
        page = Paginator(ret, 10)
        page_id = request.GET.get('page_id')
        if page_id == None:
            page_id = 1
        stus = page.page(int(page_id))
        names = ''
        return render(request, 'back/back.html',{'ret': stus, 'error_msg': error_msg, 'press_obj': names, 'pageid': int(page_id),'page': page, 'menu': menus, 'list': int(list), 'user': user})
    else:
        namea = names.lstrip()  # 去除开头空格
        name = namea.rstrip()  # 去除结尾空格
        ret = machine.objects.filter(Q(ip=name) | Q(ip1=name) | Q(purpose=name) | Q(user=name) | Q(post=name)| Q(pwd=name)| Q(create_date=name)| Q(name=name)| Q(emil=name)| Q(status=name)| Q(relevance=name)| Q(remark=name))
        if len(ret) == 0:
            ret = machine.objects.all().order_by("-create_date")
        page = Paginator(ret, 10)
        page_id = request.GET.get('page_id')
        if page_id == None:
            page_id = 1
        stus = page.page(page_id)
        return render(request, 'back/back.html',{'ret': stus, 'error_msg': error_msg, 'press_obj': names, 'pageid': int(page_id),'page': page, 'menu': menus, 'list':int(list), 'user': user})


@auth
def add_back(request):
    list = request.GET.get('list')
    user = request.GET.get('user')

    error_msg = ''
    if request.method == 'POST':
        #取用户数据
        #写入数据库
        back_ip = request.POST.get('ip')
        back_ip1 = request.POST.get('ip1')
        back_user = request.POST.get('user')
        back_pwd = request.POST.get('pwd')
        back_post = request.POST.get('post')
        back_timestart = time.strftime("%Y-%m-%d", time.localtime())
        back_name = request.POST.get('name')
        back_emil = request.POST.get('emil')
        back_purpose = request.POST.get('purpose')
        back_remark = request.POST.get('remark')
        machine.objects.create(ip = back_ip,
                               ip1=back_ip1,
                               user=back_user,
                               pwd=back_pwd,
                               post=back_post,
                               create_date=back_timestart,
                               name=back_name,
                               emil=back_emil,
                               remark=back_remark,
                               purpose=back_purpose
                               )
        return redirect('/systemctl/back?user=' + user + '&list=' + list)  # 验证成功跳转
    return render(request,'back/add_back.html',{'error_msg': error_msg, 'list': int(list), 'user': user})

@auth
def edit_back(request):
    list = request.GET.get('list')
    user = request.GET.get('user')
    edit_id = request.GET.get('id')
    # 1. 从URL中获取要编辑的出版社的id
    if request.method == 'POST':
        back_ip = request.POST.get('ip')
        back_ip1 = request.POST.get('ip1')
        back_user = request.POST.get('user')
        back_pwd = request.POST.get('pwd')
        back_post = request.POST.get('post')
        back_name = request.POST.get('name')
        back_emil = request.POST.get('emil')
        back_remark = request.POST.get('remark')
        back_purpose = request.POST.get('purpose')
        edit_back_obj = machine.objects.get(id=edit_id)
        edit_back_obj.ip = back_ip
        edit_back_obj.ip1 = back_ip1
        edit_back_obj.user = back_user
        edit_back_obj.pwd = back_pwd
        edit_back_obj.post = back_post
        edit_back_obj.name = back_name
        edit_back_obj.emil = back_emil
        edit_back_obj.remark = back_remark
        edit_back_obj.purpose = back_purpose
        edit_back_obj.save()
        return redirect('/systemctl/back?user=' + user + '&list=' + list)
    ret = machine.objects.get(id=edit_id)
    return render(request, 'back/edit_back.html', {'press_obj': ret, 'list': int(list), 'user': user})

@auth
def del_back(request):
    list = request.GET.get('list')
    user = request.GET.get('user')
    edit_id = request.GET.get('id')
    # 1. 从URL中获取要编辑的出版社的id
    if request.method == 'GET':
        machine.objects.filter(id=edit_id).delete()
        return redirect('/systemctl/back?user=' + user + '&list=' + list)

@auth
def install(request):
    list = request.GET.get('list')
    user = request.GET.get('user')
    edit_id = request.GET.get('id')
    if request.method == 'POST':
        edit_id = request.GET.get('nameid')
        machine_obj = machine.objects.get(id=edit_id)
        install = request.POST.get('inastllid')
        serviceinstall_obj = Command.objects.get(id=install)
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(hostname=machine_obj.ip, port=machine_obj.post, username=machine_obj.user, password=machine_obj.pwd)

        for cmd in [serviceinstall_obj.cmd1, serviceinstall_obj.cmd2, serviceinstall_obj.cmd3, serviceinstall_obj.cmd4, serviceinstall_obj.cmd5, serviceinstall_obj.cmd6, serviceinstall_obj.cmd7, serviceinstall_obj.cmd8, serviceinstall_obj.cmd9]:
            if cmd == None or cmd == "":
                continue
            stdin, stdout, stderr = ssh.exec_command(cmd, get_pty=True)
            res, err = stdout.read(), stderr.read()
            if err:
                print(err.decode())
            print(res.decode())
        ssh.close()
        return redirect('/systemctl/back?user=' + user + '&list=' + list)
    ret = Command.objects.all().order_by("-create_date")
    return render(request, 'back/install.html', {'press_obj': ret,'nameid':edit_id, 'list': int(list), 'user': user})


@auth
def listcommand(request):
    list = request.GET.get('list')
    user = request.GET.get('user')
    ret = Command.objects.all().order_by("-create_date")
    return render(request, 'command/listcommand.html', {'ret': ret, 'menu': menu, 'list': int(list), 'user': user})

@auth
def addcommand(request):
    error_msg = ''
    list = request.GET.get('list')
    user = request.GET.get('user')
    if request.method == 'POST':
        command_name = request.POST.get('name')
        ret = Command.objects.filter(name=command_name)
        if ret:
            error_msg = '名称已存在'
            # 取用户数据
            # 写入数据库
        else:
            cmd_name = request.POST.get('name')
            cmd_timedate = time.strftime("%Y-%m-%d", time.localtime())
            remark = request.POST.get('remark')
            cmd1 = request.POST.get('cmd1')
            cmd2 = request.POST.get('cmd2')
            cmd3 = request.POST.get('cmd3')
            cmd4 = request.POST.get('cmd4')
            cmd5 = request.POST.get('cmd5')
            cmd6 = request.POST.get('cmd6')
            cmd7 = request.POST.get('cmd7')
            cmd8 = request.POST.get('cmd8')
            cmd9 = request.POST.get('cmd9')
            Command.objects.create(name=cmd_name, cmd1=cmd1, cmd2=cmd2, cmd3=cmd3, cmd4=cmd4, cmd5=cmd5, cmd6=cmd6, cmd7=cmd7, cmd8=cmd8, cmd9=cmd9, create_date=cmd_timedate, remark=remark)
            return redirect('/systemctl/listcommand?user=' + user + '&list=' + list)  # 验证成功跳转
    return render(request,'command/addcommand.html',{'error_msg': error_msg, 'list': int(list), 'user': user})

@auth
def editcommand(request):
    list = request.GET.get('list')
    user = request.GET.get('user')
    edit_id = request.GET.get('id')
    # 1. 从URL中获取要编辑的id
    if request.method == 'POST':
        cmd_name = request.POST.get('name')
        remark = request.POST.get('remark')
        cmd1 = request.POST.get('cmd1')
        cmd2 = request.POST.get('cmd2')
        cmd3 = request.POST.get('cmd3')
        cmd4 = request.POST.get('cmd4')
        cmd5 = request.POST.get('cmd5')
        cmd6 = request.POST.get('cmd6')
        cmd7 = request.POST.get('cmd7')
        cmd8 = request.POST.get('cmd8')
        cmd9 = request.POST.get('cmd9')
        edit_user_obj = Command.objects.get(id=edit_id)
        edit_user_obj.name = cmd_name
        edit_user_obj.cmd1 = cmd1
        edit_user_obj.cmd2 = cmd2
        edit_user_obj.cmd3 = cmd3
        edit_user_obj.cmd4 = cmd4
        edit_user_obj.cmd5 = cmd5
        edit_user_obj.cmd6 = cmd6
        edit_user_obj.cmd7 = cmd7
        edit_user_obj.cmd8 = cmd8
        edit_user_obj.cmd9 = cmd9
        edit_user_obj.remark = remark
        edit_user_obj.save()
        return redirect('/systemctl/listcommand?user=' + user + '&list=' + list)  # 验证成功跳转
    ret = Command.objects.get(id=edit_id)
    return render(request, 'command/editcommand.html', {'ret': ret, 'list': int(list), 'user': user})

@auth
def delcommand(request):
    list = request.GET.get('list')
    user = request.GET.get('user')
    edit_id = request.GET.get('id')
    if request.method == 'GET':
        Command.objects.filter(id=edit_id).delete()
        return redirect('/systemctl/listcommand?user=' + user + '&list=' + list)



@auth
def listconf(request):
    list = request.GET.get('list')
    user = request.GET.get('user')
    ret = conf.objects.all().order_by("-create_date")
    return render(request, 'config/listconfig.html',{'ret': ret, 'list': int(list), 'user':user})


@auth
def addconf(request):
    list = request.GET.get('list')
    user = request.GET.get('user')
    error_msg = ''
    if request.method == 'POST':
        press_name = request.POST.get('servername')
        ret = conf.objects.filter(servername=press_name)
        if ret:
            error_msg = '服务名称已存在'
            # 取用户数据
            # 写入数据库
        else:
            press_servername = request.POST.get('servername')
            press_ip = request.POST.get('ip')
            press_port = request.POST.get('port')
            press_timedate = time.strftime("%Y-%m-%d", time.localtime())
            press_user = request.POST.get('user')
            press_pwd = request.POST.get('pwd')
            press_token = request.POST.get('token')
            press_remark = request.POST.get('remark')
            conf.objects.create(servername=press_servername, ip=press_ip, port=press_port, user=press_user, pwd=press_pwd, token=press_token, create_date=press_timedate, remark=press_remark)
            return redirect('/systemctl/listconf?user=' + user + '&list=' + list)  # 验证成功跳转
    return render(request,'config/addconfig.html',{'error_msg': error_msg, 'list': int(list), 'user': user})


@auth
def editconf(request):
    list = request.GET.get('list')
    user = request.GET.get('user')
    edit_id = request.GET.get('id')
    # 1. 从URL中获取要编辑的id
    if request.method == 'POST':
        # press_servername = request.POST.get('servername')
        press_ip = request.POST.get('ip')
        press_port = request.POST.get('port')
        press_user = request.POST.get('user')
        press_pwd = request.POST.get('pwd')
        press_token = request.POST.get('token')
        press_remark = request.POST.get('remark')
        edit_user_obj = conf.objects.get(id=edit_id)
        # edit_user_obj.servername = press_servername
        edit_user_obj.ip = press_ip
        edit_user_obj.port = press_port
        edit_user_obj.user = press_user
        edit_user_obj.pwd = press_pwd
        edit_user_obj.token = press_token
        edit_user_obj.remark = press_remark
        edit_user_obj.save()
        return redirect('/systemctl/listconf?user=' + user + '&list=' + list)
    ret = conf.objects.get(id=edit_id)
    return render(request, 'config/editconfig.html', {'press_obj': ret, 'list': int(list), 'user': user})

@auth
def listmenu(request):
    list = request.GET.get('list')
    user = request.GET.get('user')
    ret = Menu.objects.all()
    return render(request, 'menu/listmenu.html', {'ret': ret, 'list': int(list), 'user': user})

@auth
def addmenu(request):
    error_msg = ''
    list = request.GET.get('list')
    user = request.GET.get('user')
    if request.method == 'POST':
        menu_name = request.POST.get('name')
        ret = Menu.objects.filter(name=menu_name)
        if ret:
            error_msg = '名称已存在'
            # 取用户数据
            # 写入数据库
        else:
            name = request.POST.get('name')
            remark = request.POST.get('remark')
            url = request.POST.get('url')
            type = request.POST.get('type')
            Menu.objects.create(name=name, type=type, url=url, remark=remark)
            return redirect('/systemctl/listmenu?user=' + user + '&list=' + list)  # 验证成功跳转
    return render(request,'menu/addmenu.html',{'error_msg': error_msg, 'list': int(list), 'user': user})

@auth
def editmenu(request):
    list = request.GET.get('list')
    user = request.GET.get('user')
    edit_id = request.GET.get('id')
    # 1. 从URL中获取要编辑的id
    if request.method == 'POST':
        cmd_name = request.POST.get('name')
        remark = request.POST.get('remark')
        url = request.POST.get('url')
        type = request.POST.get('type')
        edit_obj = Menu.objects.get(id=edit_id)
        edit_obj.name = cmd_name
        edit_obj.outer_ip = type
        edit_obj.url = url
        edit_obj.remark = remark
        edit_obj.save()
        return redirect('/systemctl/listmenu?user=' + user + '&list=' + list)  # 验证成功跳转
    ret = Menu.objects.get(id=edit_id)
    return render(request, 'menu/editmenu.html', {'ret': ret, 'list': int(list), 'user': user})

@auth
def delmenu(request):
    list = request.GET.get('list')
    user = request.GET.get('user')
    edit_id = request.GET.get('id')
    if request.method == 'GET':
        Menu.objects.filter(id=edit_id).delete()
        Role_menu.objects.filter(menuid=edit_id).delete()
        return redirect('/systemctl/listmenu?user=' + user + '&list=' + list)

@auth
def listrole(request):
    list = request.GET.get('list')
    user = request.GET.get('user')
    ret = Role.objects.all()
    return render(request, 'role/listrole.html', {'ret': ret, 'list': int(list), 'user': user})

@auth
def addrole(request):
    error_msg = ''
    list = request.GET.get('list')
    user = request.GET.get('user')
    menu = Menu.objects.all()
    roletest = Role_menu.objects.filter(roleid=3)
    rolelist = []
    for i in roletest:
        rolelist.append(int(i.menuid))
    if request.method == 'POST':
        role_name = request.POST.get('name')
        if not role_name:
            error_msg = '名称不能为空'
            return render(request, 'role/addrole.html',{'error_msg': error_msg, 'list': int(list), 'user': user, 'menu': menu})
        ret = Menu.objects.filter(name=role_name)
        if ret:
            error_msg = '名称已存在'
            # 取用户数据
            # 写入数据库
        else:
            name = request.POST.get('name')
            remark = request.POST.get('remark')
            timedate = time.strftime("%Y-%m-%d", time.localtime())
            Role.objects.create(name=name, type=name, remark=remark, create_date=timedate)
            role_obj = Role.objects.get(name=name)
            role_obj.jurisdiction = role_obj.id
            role_obj.save()
            role_obj = Role.objects.get(name=name)
            roles = request.POST.getlist('role')
            for i in roles:
                remark = ''
                Role_menu.objects.create(roleid=role_obj.id, menuid=i, remark=remark)
            return redirect('/systemctl/listrole?user=' + user + '&list=' + list)  # 验证成功跳转
    return render(request,'role/addrole.html',{'error_msg': error_msg, 'list': int(list), 'user': user, 'menu':menu, 'roletest': rolelist})

@auth
def editrole(request):
    list = request.GET.get('list')
    user = request.GET.get('user')
    edit_id = request.GET.get('id')
    menu = Menu.objects.all()
    roletest = Role_menu.objects.filter(roleid=edit_id)
    rolelist = []
    for i in roletest:
        rolelist.append(int(i.menuid))
    # 1. 从URL中获取要编辑的id
    if request.method == 'POST':
        remark = request.POST.get('remark')
        edit_obj = Role.objects.get(id=edit_id)
        edit_obj.remark = remark
        edit_obj.save()
        roles = request.POST.getlist('role')
        role_obj = Role.objects.get(id=edit_id)
        Role_menu.objects.filter(roleid=edit_id).delete()
        for i in roles:
            remark = ''
            Role_menu.objects.create(roleid=role_obj.id, menuid=i, remark=remark)
        return redirect('/systemctl/listrole?user=' + user + '&list=' + list)  # 验证成功跳转
    ret = Role.objects.get(id=edit_id)
    return render(request, 'role/editrole.html', {'ret': ret, 'list': int(list), 'user': user, 'menu':menu, 'roletest': rolelist})

@auth
def delrole(request):
    list = request.GET.get('list')
    user = request.GET.get('user')
    edit_id = request.GET.get('id')
    if request.method == 'GET':
        Role.objects.filter(id=edit_id).delete()
        Role_menu.objects.filter(roleid=edit_id).delete()
        return redirect('/systemctl/listrole?user=' + user + '&list=' + list)


@auth
def listproduct(request):
    list = request.GET.get('list')
    user = request.GET.get('user')
    ret = Host_Machine.objects.all()
    return render(request, 'product/listproduct.html', {'ret': ret, 'list': int(list), 'user': user})


@auth
def addproduct(request):
    error_msg = ''
    list = request.GET.get('list')
    user = request.GET.get('user')
    if request.method == 'POST':
        machine_name = request.POST.get('name')

        ret = Host_Machine.objects.filter(name=machine_name)
        if ret:
            error_msg = '名称已存在'
            # 取用户数据
            # 写入数据库
        else:
            name = request.POST.get('name')
            remark = request.POST.get('remark')
            nameuser = request.POST.get('nameuser')
            sn_code = request.POST.get('sn_code')
            cpu = request.POST.get('cpu')
            memory = request.POST.get('memory')
            disk = request.POST.get('disk')
            system = request.POST.get('system')
            pwd = request.POST.get('pwd')
            outer_ip = request.POST.get('outer_ip')
            timedate = time.strftime("%Y-%m-%d", time.localtime())
            Host_Machine.objects.create(name=name,
                                        nameuser=user,
                                        remark=remark,
                                        create_date=timedate,
                                        sn_code=sn_code,
                                        cpu=cpu,
                                        memory=memory,
                                        disk=disk,
                                        system=system,
                                        username=user,
                                        pwd=pwd,
                                        outer_ip=outer_ip)
            return redirect('/systemctl/listproduct?user=' + user + '&list=' + list)  # 验证成功跳转
    return render(request,'product/addproduct.html',{'error_msg': error_msg, 'list': int(list), 'user': user})


@auth
def editproduct(request):
    list = request.GET.get('list')
    user = request.GET.get('user')
    edit_id = request.GET.get('id')
    # 1. 从URL中获取要编辑的id
    if request.method == 'POST':
        name = request.POST.get('name')
        remark = request.POST.get('remark')
        sn_code = request.POST.get('sn_code')
        cpu = request.POST.get('cpu')
        memory = request.POST.get('memory')
        disk = request.POST.get('disk')
        system = request.POST.get('system')
        username = request.POST.get('username')
        pwd = request.POST.get('pwd')
        outer_ip = request.POST.get('outer_ip')
        edit_obj = Host_Machine.objects.get(id=edit_id)
        edit_obj.name = name
        edit_obj.sn_code = sn_code
        edit_obj.cpu = cpu
        edit_obj.memory = memory
        edit_obj.disk = disk
        edit_obj.system = system
        edit_obj.username = username
        edit_obj.pwd = pwd
        edit_obj.outer_ip = outer_ip
        edit_obj.nameuser = user
        edit_obj.remark = remark
        edit_obj.save()
        return redirect('/systemctl/listproduct?user=' + user + '&list=' + list)  # 验证成功跳转
    ret = Host_Machine.objects.get(id=edit_id)
    return render(request, 'product/editproduct.html', {'ret': ret, 'list': int(list), 'user': user})

@auth
def delproduct(request):
    list = request.GET.get('list')
    user = request.GET.get('user')
    edit_id = request.GET.get('id')
    if request.method == 'GET':
        Host_Machine.objects.filter(id=edit_id).delete()
        Users_group_hm.objects.filter(hmid=edit_id).delete()
        return redirect('/product/listproduct?user=' + user + '&list=' + list)



@auth
def listgroup(request):
    list = request.GET.get('list')
    user = request.GET.get('user')
    ret = Users_group.objects.all()
    return render(request, 'group/list.html', {'ret': ret, 'list': int(list), 'user': user})

@auth
def addgroup(request):
    error_msg = ''
    list = request.GET.get('list')
    user = request.GET.get('user')
    menu = Host_Machine.objects.all()
    if request.method == 'POST':
        role_name = request.POST.get('name')
        if not role_name:
            error_msg = '名称不能为空'
            return render(request, 'group/add.html',{'error_msg': error_msg, 'list': int(list), 'user': user, 'menu': menu})
        ret = Users_group.objects.filter(name=role_name)
        if ret:
            error_msg = '名称已存在'
            # 取用户数据
            # 写入数据库
        else:
            name = request.POST.get('name')
            remark = request.POST.get('remark')
            timedate = time.strftime("%Y-%m-%d", time.localtime())
            Users_group.objects.create(name=name, remark=remark, create_date=timedate)
            group_obj = Users_group.objects.get(name=name)
            groups = request.POST.getlist('role')
            for i in groups:
                remark = ''
                Users_group_hm.objects.create(groupid=group_obj.id, hmid=i, remark=remark)
            return redirect('/systemctl/listgroup?user=' + user + '&list=' + list)  # 验证成功跳转
    return render(request,'group/add.html',{'error_msg': error_msg, 'list': int(list), 'user': user, 'menu':menu})

@auth
def editgroup(request):
    list = request.GET.get('list')
    user = request.GET.get('user')
    edit_id = request.GET.get('id')
    menu = Host_Machine.objects.all()
    grouptest = Users_group_hm.objects.filter(groupid=edit_id)
    grouplist = []
    for i in grouptest:
        grouplist.append(int(i.hmid))
    # 1. 从URL中获取要编辑的id
    if request.method == 'POST':
        remark = request.POST.get('remark')
        edit_obj = Users_group.objects.get(id=edit_id)
        edit_obj.remark = remark
        edit_obj.save()
        roles = request.POST.getlist('role')
        group_obj = Users_group.objects.get(id=edit_id)
        Users_group_hm.objects.filter(groupid=edit_id).delete()
        for i in roles:
            remark = ''
            Users_group_hm.objects.create(groupid=group_obj.id, hmid=i, remark=remark)
        return redirect('/systemctl/listgroup?user=' + user + '&list=' + list)  # 验证成功跳转
    ret = Users_group.objects.get(id=edit_id)
    return render(request, 'group/edit.html', {'ret': ret, 'list': int(list), 'user': user, 'menu':menu, 'roletest': grouplist})

@auth
def delgroup(request):
    list = request.GET.get('list')
    user = request.GET.get('user')
    edit_id = request.GET.get('id')
    if request.method == 'GET':
        Users_group.objects.filter(id=edit_id).delete()
        Users_group_hm.objects.filter(groupid=edit_id).delete()
        return redirect('/systemctl/listgroup?user=' + user + '&list=' + list)

@auth
def listuser(request):
    list = request.GET.get('list')
    user = request.GET.get('user')
    ret = Users.objects.all()
    return render(request, 'user/list.html', {'ret': ret, 'list': int(list), 'user': user})

@auth
def adduser(request):
    error_msg = ''
    list = request.GET.get('list')
    user = request.GET.get('user')
    role = Role.objects.all()
    user_group = Users_group.objects.all()
    if request.method == 'POST':
        role_name = request.POST.get('username')
        if not role_name:
            error_msg = '用户名不能为空'
            return render(request, 'user/add.html',{'error_msg': error_msg, 'list': int(list), 'user': user, 'role': role, 'usergroup': user_group})
        ret = Users.objects.filter(name=role_name)
        if ret:
            error_msg = '名称已存在'
            # 取用户数据
            # 写入数据库
            return render(request, 'user/add.html',{'error_msg': error_msg, 'list': int(list), 'user': user, 'role': role, 'usergroup': user_group})
        else:
            name = request.POST.get('name')
            pwd = request.POST.get('pwd')
            username = request.POST.get('username')
            role = request.POST.get('role')
            emil = request.POST.get('emil')
            remark = request.POST.get('remark')
            timedate = time.strftime("%Y-%m-%d", time.localtime())
            Users.objects.create(name=name, remark=remark, create_date=timedate, pwd=pwd, username=username, emil=emil)
            user_obj = Users.objects.get(name=name)
            remark = ''
            Users_role.objects.create(userid=user_obj.id, roleid=role, remark=remark)
            groups = request.POST.getlist('group')
            for i in groups:
                remark = ''
                Users_group_relevance.objects.create(groupid=i, usersid=user_obj.id, remark=remark)
            return redirect('/systemctl/listuser?user=' + user + '&list=' + list)  # 验证成功跳转
    return render(request,'user/add.html',{'error_msg': error_msg, 'list': int(list), 'user': user, 'role':role, 'usergroup': user_group})



@auth
def edituser(request):
    list = request.GET.get('list')
    user = request.GET.get('user')
    edit_id = request.GET.get('id')
    role = Role.objects.all()
    userrole = Users_role.objects.get(userid=edit_id)
    userroles = Role.objects.get(id=userrole.roleid)
    user_group = Users_group.objects.all()
    grouptest = Users_group_relevance.objects.filter(usersid=edit_id)
    grouplist = []
    for i in grouptest:
        grouplist.append(int(i.groupid))
    # 1. 从URL中获取要编辑的id
    if request.method == 'POST':
        name = request.POST.get('name')
        pwd = request.POST.get('pwd')
        username = request.POST.get('username')
        role = request.POST.get('role')
        emil = request.POST.get('emil')
        remark = request.POST.get('remark')
        edit_obj = Users.objects.get(id=edit_id)
        edit_obj.remark = remark
        edit_obj.emil = emil
        edit_obj.username = username
        edit_obj.name = name
        edit_obj.pwd = pwd
        edit_obj.save()
        user_obj = Users.objects.get(name=name)
        remark = ''
        Users_role.objects.filter(userid=user_obj.id).delete()
        Users_role.objects.create(userid=user_obj.id, roleid=role, remark=remark)
        groups = request.POST.getlist('group')
        Users_group_relevance.objects.filter(usersid=edit_id).delete()
        for i in groups:
            remark = ''
            Users_group_relevance.objects.create(groupid=i, usersid=user_obj.id, remark=remark)
        return redirect('/systemctl/listuser?user=' + user + '&list=' + list)  # 验证成功跳转
    ret = Users.objects.get(id=edit_id)
    return render(request, 'user/edit.html', {'ret': ret, 'list': int(list), 'user': user, 'role':role, 'usergroup': user_group, 'userroles':userroles, 'grouplist':grouplist})


@auth
def deluser(request):
    list = request.GET.get('list')
    user = request.GET.get('user')
    edit_id = request.GET.get('id')
    if request.method == 'GET':
        Users.objects.filter(id=edit_id).delete()
        Users_role.objects.filter(userid=edit_id).delete()
        Users_group_relevance.objects.filter(usersid=edit_id).delete()
        return redirect('/systemctl/listuser?user=' + user + '&list=' + list)


def health(request):
    return HttpResponse(status=200, content_type='application/json')

















@auth
def listtemplates(request):
    list = request.GET.get('list')
    user = request.GET.get('user')
    ret = Pipelinetemplates.objects.all()
    return render(request, 'pipelinetemplates/list.html', {'ret': ret, 'list': int(list), 'user': user})

@auth
def addtemplates(request):
    error_msg = ''
    list = request.GET.get('list')
    user = request.GET.get('user')
    if request.method == 'POST':
        role_name = request.POST.get('name')
        templates = request.POST.get('templates')
        print(templates)
        if not role_name or not templates:
            error_msg = '用户名和模板不能为空'
            return render(request, 'pipelinetemplates/add.html',{'error_msg': error_msg, 'list': int(list), 'user': user})
        ret = Pipelinetemplates.objects.filter(name=role_name)
        if ret:
            error_msg = '名称已存在'
            # 取用户数据
            # 写入数据库
            return render(request, 'pipelinetemplates/add.html',{'error_msg': error_msg, 'list': int(list), 'user': user})
        else:
            remark = request.POST.get('remark')
            if not remark:
                remark = ''
            Pipelinetemplates.objects.create(name=role_name, remark=remark, templates=templates)
            return redirect('/systemctl/listtemplates?user=' + user + '&list=' + list)  # 验证成功跳转
    return render(request,'pipelinetemplates/add.html',{'error_msg': error_msg, 'list': int(list), 'user': user})



@auth
def edittemplates(request):
    list = request.GET.get('list')
    user = request.GET.get('user')
    edit_id = request.GET.get('id')
    # 1. 从URL中获取要编辑的id
    if request.method == 'POST':
        remark = request.POST.get('remark')
        templates = request.POST.get('templates')
        edit_obj = Pipelinetemplates.objects.get(id=edit_id)
        edit_obj.remark = remark
        edit_obj.templates = templates
        edit_obj.save()
        return redirect('/systemctl/listtemplates?user=' + user + '&list=' + list)  # 验证成功跳转
    ret = Pipelinetemplates.objects.get(id=edit_id)
    return render(request, 'pipelinetemplates/edit.html', {'ret': ret, 'list': int(list), 'user': user})

@auth
def deltemplates(request):
    list = request.GET.get('list')
    user = request.GET.get('user')
    edit_id = request.GET.get('id')
    if request.method == 'GET':
        Pipelinetemplates.objects.filter(id=edit_id).delete()
        return redirect('/systemctl/listtemplates?user=' + user + '&list=' + list)


















